# monitor/routers.py
from typing import List, Tuple, Literal
from datetime import datetime, timedelta

from django.db.models import Q
from ninja import Router, Query
from django.utils import timezone
from django.http import HttpRequest
from django.db.models.manager import BaseManager

from monitor.models import ServerMetrics
from monitor.schemas import MetricsIn, MetricsOut


router = Router(tags=["性能指标"])


@router.get(
    "/metrics",
    summary="获取服务器性能指标历史数据",
    response={200: List[MetricsOut]},
)
def get_server_metrics(request: HttpRequest, params: Query[MetricsIn]) -> Tuple[Literal[200], List[MetricsOut]]:
    """获取服务器性能指标历史数据, 默认返回默认60条"""
    # 设置默认时间范围
    end_time: datetime = params.end_time or timezone.now()
    start_time: datetime = params.start_time or (end_time - timedelta(hours=1))
    # 构建查询
    query: Q = Q(time__gte=start_time, time__lte=end_time)
    # 执行查询
    metrics_queryset: BaseManager[ServerMetrics] = ServerMetrics.objects.filter(query).order_by("-time")[: params.limit]
    # 将模型实例转换为 MetricsOut Schema 实例列表
    return 200, [MetricsOut.model_validate(metric) for metric in metrics_queryset]


@router.get(
    "/metrics/latest",
    summary="获取最新的服务器性能指标",
    response={200: MetricsOut},
)
def get_latest_metrics(request: HttpRequest) -> Tuple[Literal[200], MetricsOut]:
    """获取最新的服务器性能指标"""
    latest_metric: ServerMetrics | None = ServerMetrics.objects.order_by("-time").first()
    return 200, MetricsOut.model_validate(latest_metric)
